<!--
 * @Author: lihaogn
 * @Date: 2023-08-23 22:10:10
 * @LastEditTime: 2023-08-23 22:12:29
 * @LastEditor: lihaogn
 * @Description: 
 * @FilePath: \lix-js-demo\js判断文字是否超出需要省略号\index.html
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>判断文字超出显示省略号-方法1</title>
  <style>
    .ellipsis {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .box {
      border: 1px solid gray;
      padding: 10px;
    }
  </style>
</head>

<body>
  <div class="ellipsis box">
    Lorem ipsum dolor sit amet consectetur adipisicing elit.
  </div>

  <script>
    const getPadding = (el) => {
      const style = window.getComputedStyle(el, null)
      const paddingLeft = Number.parseInt(style.paddingLeft, 10) || 0
      const paddingRight = Number.parseInt(style.paddingRight, 10) || 0
      const paddingTop = Number.parseInt(style.paddingTop, 10) || 0
      const paddingBottom = Number.parseInt(style.paddingBottom, 10) || 0
      return {
        left: paddingLeft,
        right: paddingRight,
        top: paddingTop,
        bottom: paddingBottom,
      }
    }

    const checkEllipsis = () => {
      let result = {}
      const box = document.querySelector('.box')
      const range = document.createRange();
      range.setStart(box, 0)
      range.setEnd(box, box.childNodes.length)
      let rangeWidth = range.getBoundingClientRect().width
      let rangeHeight = range.getBoundingClientRect().height

      const offsetWidth = rangeWidth - Math.floor(rangeWidth)
      if (offsetWidth < 0.001) {
        rangeWidth = Math.floor(rangeWidth)
      }
      const offsetHeight = rangeHeight - Math.floor(rangeHeight)
      if (offsetHeight < 0.001) {
        rangeHeight = Math.floor(rangeHeight)
      }


      const { top, left, right, bottom } = getPadding(box)
      const horizontalPadding = left + right
      const verticalPadding = top + bottom


      if (rangeWidth + horizontalPadding > box.offsetWidth ||
        rangeHeight + verticalPadding > box.offsetHeight ||
        box.scrollWidth > box.offsetWidth) {
        result.textContent = '存在省略号'
      } else {
        result.textContent = '容器宽度足够，没有省略号了'
      }
      console.log('result:', result);
    }

    checkEllipsis()
  </script>
</body>

</html>